import dayjs from "dayjs";
import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
// import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, h } from "vue";
import type { FormItemProps } from "../utils/types";
import { isAllEmpty, deviceDetection } from "@pureadmin/utils"; // cloneDeep,
import { getResourcesList, addResources, updateResources } from "@/api/rsapi";

export function useRes() {
  const form = reactive({
    name: "",
    ordinal: 0,
    editable: 0,
    remark: ""
  });

  const formRef = ref();
  const dataList = ref([]);
  const loading = ref(true);
  // const { tagStyle } = usePublicHooks();

  const columns: TableColumnList = [
    {
      label: "资源名称",
      prop: "name",
      width: 180,
      align: "left"
    },
    {
      label: "资源路径",
      prop: "pattern",
      width: 180
    },
    {
      label: "排序",
      prop: "ordinal",
      minWidth: 70
    },
    // {
    //   label: "创建时间",
    //   minWidth: 200,
    //   prop: "createTime",
    //   formatter: ({ createTime }) =>
    //     dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    // },
    {
      label: "备注",
      prop: "remark",
      minWidth: 320
    },
    {
      label: "操作",
      fixed: "right",
      width: 260,
      slot: "operation"
    }
  ];

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { elements } = await getResourcesList({ page: 1, size: 1000 });
    let newData = elements;
    if (!isAllEmpty(form.name)) {
      newData = newData.filter(item => item.name.includes(form.name));
    }
    if (!isAllEmpty(form.ordinal)) {
      newData = newData.filter(item => item.ordinal === form.ordinal);
    }
    dataList.value = handleTree(newData); // 处理成树结构
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  // function formatHigherDeptOptions(treeList) {
  //   if (!treeList || !treeList.length) return;
  //   const newTreeList = [];
  //   for (let i = 0; i < treeList.length; i++) {
  //     treeList[i].disabled = treeList[i].status === 0 ? true : false;
  //     formatHigherDeptOptions(treeList[i].children);
  //     newTreeList.push(treeList[i]);
  //   }
  //   return newTreeList;
  // }

  function openDialog(title = "新增", row?: FormItemProps) {
    addDialog({
      title: `${title}资源`,
      props: {
        formInline: {
          id: row?.id ?? 0,
          name: row?.name ?? "",
          pattern: row?.pattern ?? "",
          ordinal: row?.ordinal ?? 0,
          remark: row?.remark ?? ""
        }
      },
      width: "40%",
      draggable: false,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了资源名称为${curData.name}的数据`, {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            if (title === "新增") {
              let tempData = {
                name: curData.name,
                pattern: curData.pattern,
                ordinal: curData.ordinal,
                remark: curData.remark
              };
              const { id } = await addResources(tempData);
              if (id) {
                chores();
              }
            } else {
              const { id } = await updateResources({ id: curData.id });
              if (id) {
                chores();
              }
            }
          }
        });
      }
    });
  }

  function handleDelete(row) {
    message(`您删除了资源名称为${row.name}的数据`, { type: "success" });
    onSearch();
  }

  onMounted(() => {
    console.log(dayjs().format("YYYY-MM-DD HH:mm:ss"));
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    dataList,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改资源 */
    openDialog,
    /** 删除资源 */
    handleDelete,
    handleSelectionChange
  };
}
